<?php
/**
 * Created by PhpStorm.
 * User: LFL
 * Date: 2010/5/25
 * Time: 16:02
 */
namespace backend\controllers;

use Yii;
use yii\web\AdminController;
use backend\models\Warehouse;
use backend\models\Shop;
use backend\models\Bill;

class BillDiffController extends AdminController
{
    public $layout = false;
    //业务关键字
    public $service = 'BillDiff';

    public function actionIndex()
    {
        return $this->render('index');
    }

    //jax订单列表
    public function actionGetList()
    {
        $data = Yii::$app->request->post();
        $sql_list = 'SELECT * FROM j_diff WHERE 1=1 ';
        $sql_count = 'SELECT COUNT(0) CNT FROM j_diff WHERE 1=1 ';

        $sql = '';
        //搜索关键字
        if (!empty($data['searchCode'])) {
            $sql .= ' And billNo like "%' . $data['searchCode'] . '%"';
        }
        if (isset($data['status']) && in_array($data['status'], array('0', '1', '9'))) {
            $sql .= ' And diffStatus=' . $data['status'];
        }

        $list_count = Yii::$app->db->createCommand($sql_count . $sql)->queryOne();
        $count = $list_count['CNT'];

        $list = array();
        if ($count) {
            $sort_string = $sort = '';
            if (isset($data['order']) && isset($data['order'][0]['column'])) {
                $sort_string .= empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
                $sort = $data['order'][0]['dir'] == 'asc' ? 'asc' : 'desc';
            }
            $sql .= ' ORDER BY ' . $sort_string . ' ' . $sort;
            if ($data['start'] || $data['length']) {
                $sql .= ' limit ' . $data['start'] . ',' . $data['length'];
            }
            $list = Yii::$app->db->createCommand($sql_list . $sql)->queryAll();
        }

        //相关参数 http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        //操作日志
        return \yii\helpers\Json::encode($result);
    }

    //详情信息
    public function actionGetDtl()
    {
        $data = Yii::$app->request->post();

        if (!isset($data['billNo']) || empty($data['billNo'])) {
            $this->retJson('参数错误', 500);
        }

        $sql = "SELECT * FROM j_diff WHERE billNo='" . $data['billNo'] . "'";
        $result = Yii::$app->db->createCommand($sql)->queryOne();

        if (!$result) $this->retJson('未找到单据信息', 500);

        $statusName = '';
        if ($result['diffStatus'] == '0') $statusName = '创建';
        if ($result['diffStatus'] == '1') $statusName = '已审核';
        if ($result['diffStatus'] == '9') $statusName = '作废';
        $result['statusName'] = $statusName;

        $sql = "SELECT dd.*,ma.materielCode,ma.materielName,wh.warehouseName,sup.supplierName,jbd.remark
                FROM j_diff_dtl dd
                INNER JOIN j_materiel ma on dd.materielId=ma.id
                INNER JOIN j_warehouse wh on ma.warehouseId=wh.id
                INNER JOIN j_supplier sup on ma.supplierId=sup.id
                INNER JOIN j_bill_dtl jbd on jbd.billNo = dd.billNo AND jbd.materielId = dd.materielId
                WHERE dd.billNo='" . $data['billNo'] . "'";
        $dtl = Yii::$app->db->createCommand($sql)->queryAll();
        $result['dtl'] = $dtl;
        $this->retJson('ok', 200, $result);
    }

    //查询订单发货批次数据
    public function actionCheckDiff()
    {
        $data = Yii::$app->request->post();

        if (!isset($data['billNo']) || empty($data['billNo']) || !isset($data['materielId']) || empty($data['materielId'])) {
            $this->retJson('参数错误', 500);
        }

        $sql = "SELECT bb.*,ma.materielCode,ma.materielName,ms.batch,dib.whQty,dib.shQty,dib.remark FROM j_bill_batch bb
                INNER JOIN j_materiel_stock ms ON bb.stockId=ms.id
                INNER JOIN j_materiel ma ON bb.materielId=ma.id
                LEFT JOIN j_diff_batch dib ON dib.billNo=bb.billNo AND dib.batch=ms.batch
                WHERE bb.billNo='" . $data['billNo'] . "' AND bb.materielId='" . $data['materielId'] . "'";
        $batchRes = Yii::$app->db->createCommand($sql)->queryAll();

        $this->retJson('ok', 200, $batchRes);
    }

    //审核异常单 修改批次数据
    public function actionAuditDiff()
    {
        $data = Yii::$app->request->post();

        if (!isset($data['billNo']) || empty($data['billNo']) || !isset($data['batchData']) || empty($data['batchData'])) {
            $this->retJson('参数错误', 500);
        }

        $model = new Bill();
        $sql = "SELECT * FROM j_bill WHERE billNo = '" . $data['billNo'] . "'";
        $bill = Yii::$app->db->createCommand($sql)->queryOne();

        $remark = (isset($data['remark']) && !empty($data['remark'])) ? $data['remark'] : '';

        $newTime = date('Y-m-d H:i:s');
        $strSql = '';
        $diffBatch = array();
        foreach ($data['batchData'] as $key => $batchData) {
            foreach ($batchData['batch'] as $diff) {
                $diffBatch[] = array(
                    'creator' => $model->getCreator(),
                    'createTime' => $newTime,
                    'billNo' => $data['billNo'],
                    'materielId' => $key,
                    'batch' => $diff['batch'],
                    'whQty' => $diff['whQty'],
                    'shQty' => $diff['shQty'],
                    'remark' => $diff['remark'],
                );

                //仓库认领异常数量 要将对应的库存数回滚
                if ($diff['whQty']) {
                    $strSql .= "UPDATE j_materiel_stock SET qty=qty+" . $diff['whQty'] . ",total=total+" . $diff['whQty'] . ",amount= amount+(price*" . $diff['whQty'] . ") WHERE batch='" . $diff['batch'] . "' AND materielId='" . $key . "';";
                    $strSql .= "UPDATE j_shop_stock SET qty=qty-" . $diff['whQty'] . ",amount=amount-(price*" . $diff['whQty'] . ") WHERE materielId='" . $key . "' AND batch='" . $diff['batch'] . "' AND shopId='" . $bill['shopId'] . "';";
                    $strSql .= "UPDATE j_bill_batch SET receiptQty=receiptQty-" . $diff['whQty'] . ",receiptAmount=receiptAmount-(price*" . $diff['whQty'] . ") WHERE materielId='" . $key . "' AND batch='" . $diff['batch'] . "' AND billNo='" . $data['billNo'] . "';";
                }
            }
        }

        $transaction = Yii::$app->db->beginTransaction();
        try {

            foreach ($diffBatch as $dfb) {
                Yii::$app->db->createCommand()->insert('j_diff_batch', $dfb)->execute();
            }
            if ($strSql) Yii::$app->db->createCommand($strSql)->execute();
            $sql = "UPDATE j_diff SET diffStatus = 1,editor='" . $model->getCreator() . "',editTime='" . $newTime . "',remark='" . $remark . "' WHERE billNo ='" . $data['billNo'] . "'";
            Yii::$app->db->createCommand($sql)->execute();

            $transaction->commit();
            $this->retJson('操作成功', 200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            error_log("异常:" . $e->getMessage() . $e->getLine());
            $this->retJson('操作失败', 500);
        }
    }


    //作废 -- 无用，全部以审核状态结束单据
    public function actionChanageStatus()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['billNo']) || empty($data['billNo'])) {
            $this->retJson('参数错误', 500);
        }
        $model = new Bill();
        $newTime = date('Y-m-d H:i:s');
        Yii::$app->db->createCommand("UPDATE j_diff SET diffStatus = 9,editor='".$model->getCreator()."',editTime='".$newTime."' WHERE billNo ='" . $data['billNo'] . "'")->execute();
        $this->retJson('操作成功', 200);
    }

}